package com.seed.uaa.login.impl;

import com.seed.core.exception.UserAuthenticateException;
import com.seed.core.exception.UserDisabledException;
import com.seed.core.pojo.Account;
import com.seed.core.pojo.Admin;
import com.seed.core.pojo.LoginDTO;
import com.seed.uaa.login.Login;
import com.seed.uaa.util.StpKit;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * 超级管理员登录
 */
@Slf4j
public class AdminLogin implements Login {
    private final Admin admin;

    public AdminLogin(Admin admin) {
        if(admin == null) {
            admin = new Admin();
            admin.setPassword("123456");
            admin.setEnabled(true);
        }
        this.admin = admin;
    }

    @Override
    public void login(Account account, LoginDTO dto) {
        String rawPassword = dto.getPassword();
        if(!admin.getEnabled()) {
            throw new UserDisabledException("用户名或密码错误");
        }

        if(!admin.getPassword().equals(rawPassword)) {
            throw new UserDisabledException("用户名或密码错误");
        }

        Date date = admin.getEnableTime();
        if(date != null && date.after(new Date())) {
            throw new UserDisabledException();
        }

        if(!rawPassword.equals(admin.getPassword())) {
            throw new UserAuthenticateException();
        }

        StpKit.login(account.getLoginId());
    }
}
